package app.biz.service.impl;

import app.biz.service.TccActionThree;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * The type Tcc action two.
 *
 * @author zhangsen
 */
@Component
public class TccActionThreeImpl implements TccActionThree {

    public static String operation;

    private static final Logger logger = LoggerFactory.getLogger(TccActionThreeImpl.class);

    @Override
    public boolean prepare(BusinessActionContext context) {
        return true;
    }

    /**
     * 模拟插入操作
     * @param context the action context
     * @return
     */
    @Override
    public boolean commit(BusinessActionContext context) {
        logger.info("TccAction3 COMMITED!!");
        operation="commited";
        return true;
    }

    static boolean allowsSuccess=false;
    //TODO:需要进一步了解TCC回滚失败时自动重试策略等机制
    @Override
    public boolean rollback(BusinessActionContext context) {
        logger.info("TccAction3 ROLLBACK - xid:{}", context.getXid());
        //首次执行时一定会失败
        if(allowsSuccess) {
            operation="rollbacked";
            logger.info("TccAction3 ROLLBACK Success!!");
            return true;
        }
        logger.info("TccAction3 First ROLLBACK (Failure!!)");
        operation="firstRollback";
        //允许下次回滚成功
        allowsSuccess=true;
        return false;
    }
}
